"use client"

import { useEffect, ReactNode } from "react"
import { useRouter } from "next/navigation"
import { useAuth } from "@/lib/contexts/auth-context"
import { Skeleton } from "@/components/ui/skeleton"

interface AuthGuardProps {
  children: ReactNode
  requireAuth?: boolean
  fallbackUrl?: string
}

export function AuthGuard({ children, requireAuth = false, fallbackUrl = "/login" }: AuthGuardProps) {
  const { isAuthenticated } = useAuth()
  const router = useRouter()

  useEffect(() => {
    // 如果需要认证但用户未登录，重定向到登录页
    if (requireAuth && !isAuthenticated) {
      router.push(fallbackUrl)
    }
  }, [requireAuth, isAuthenticated, router, fallbackUrl])

  // 如果需要认证但用户未登录，显示加载状态
  if (requireAuth && !isAuthenticated) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="space-y-4 text-center">
          <Skeleton className="h-8 w-48 mx-auto" />
          <Skeleton className="h-4 w-32 mx-auto" />
          <p className="text-muted-foreground text-sm">正在验证登录状态...</p>
        </div>
      </div>
    )
  }

  return <>{children}</>
}

/**
 * 保护需要登录的页面
 */
export function withAuth<P extends object>(
  Component: React.ComponentType<P>,
  fallbackUrl: string = "/login"
) {
  return function AuthenticatedComponent(props: P) {
    return (
      <AuthGuard requireAuth={true} fallbackUrl={fallbackUrl}>
        <Component {...props} />
      </AuthGuard>
    )
  }
}

/**
 * 保护已登录用户不应访问的页面（如登录、注册页）
 */
export function withGuest<P extends object>(
  Component: React.ComponentType<P>,
  redirectUrl: string = "/"
) {
  return function GuestOnlyComponent(props: P) {
    const { isAuthenticated } = useAuth()
    const router = useRouter()

    useEffect(() => {
      if (isAuthenticated) {
        router.push(redirectUrl)
      }
    }, [isAuthenticated, router])

    if (isAuthenticated) {
      return (
        <div className="min-h-screen bg-background flex items-center justify-center">
          <div className="space-y-4 text-center">
            <Skeleton className="h-8 w-48 mx-auto" />
            <p className="text-muted-foreground text-sm">正在跳转...</p>
          </div>
        </div>
      )
    }

    return <Component {...props} />
  }
}